<?php
namespace Application\Controller;

use Application\Model\Dao\UpdateDao;
use Application\Model\Dao\UserDao;
use Application\Service\PasswordService;
use Application\Service\XmlService;
use Zend\Authentication\AuthenticationService;
use Zend\View\Model\ViewModel;
use Zend\View\Model\JsonModel;
use Application\Service\ImageService;
use Application\Service\UpdateService;

class LoggedInUserController extends LoginAwareController
{
	public function logoutAction()
	{
        $userDao = $this->getServiceLocator()->get('user');
        $userDao->removeLoggedinUser($this->getLoggedinUserId());
        $auth = new AuthenticationService();
		$auth->clearIdentity();
		session_destroy();
		$this->redirect()->toUrl("/");
	}

    public function getMeAction(){
        $userDao = $this->getServiceLocator()->get('user');
        return new JsonModel($userDao->getUserByIdWithGroup($this->getLoggedinUserId()));
    }

	public function signupApartmentGetAction()
	{
		$layout = $this->layout();
		$layout->setTemplate('layout/loggedin');
		$view = new ViewModel();
		$view->setTemplate('/application/user/signup-success');
		return $view;
	}


	public function signupApartmentAction()
	{
		$req = $this->getRequest();
		$apartment = $req->getPost("apartment");
		$block = $req->getPost("block");
		$flatNo = $req->getPost("flatNo");
		$phoneNo = $req->getPost("phoneNo");
		$userDao = $this->getServiceLocator()->get('user');
		$userDao->saveAdditionalUser($this->getLoggedinUserId(), $apartment, $block, $flatNo, $phoneNo);
		$this->redirect()->toUrl("/user/signupImageGet");
	}

    public function saveHomeAddressAction(){
        $req = $this->getRequest();
        $apartment = $req->getPost("apartment");
        $block = $req->getPost("block");
        $flatNo = $req->getPost("flatNo");
        $userDao = $this->getServiceLocator()->get('user');
        $userDao->saveAdditionalUser($this->getLoggedinUserId(), $apartment, $block, $flatNo, null);
        return new JsonModel(array(result =>'success'));
    }

	public function signupImageGetAction()
	{
		$layout = $this->layout();
		$layout->setTemplate('layout/loggedin');
		$view = new ViewModel();
		$view->setTemplate('/application/user/signup-image');
		return $view;
	}

	public function profileChangeGetAction()
	{
		$layout = $this->layout()->setVariable('user', $this->getUserFromSession());
		$layout->setTemplate('layout/loggedin');
      //  var_dump($this->getUserFromSession());
		$view = new ViewModel(array('user' => $this->getUserFromSession()));
		$view->setTemplate('/application/user/profile-change');
		return $view;
	}

	public function profileChangeAction()
	{
		$request = $this->getRequest();
		$responseArray = array();
		if ($request->isPost()) {

			$post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
			$fileName = $request->getFiles('profile-image');
			$fileName = $fileName['tmp_name'];
			if($fileName != null){
				$imageService = new ImageService();
				$imageService->saveAllKindofImage($fileName, $this->getLoggedinUserId());
			}
			// Form is valid, save the form!

			// get other paremeters.
			$name = $post['name'];
			$email = $post['email'];
            $renter =  array_key_exists('renter', $post) ? $post['renter'] : 'off';
            $gender = array_key_exists('gender', $post) ? $post['gender']  : null;
            $renter = ($renter == 'on')? 1 : 0;
			$aboutMe = $post['aboutMe'];
			$flatNo = $post['flatNo'];
			$phone = $post['phone'];
			$birthDay = $post['birthDay'];
			$profession = $post['profession'];
			$secPost = $post['post'];
			$userDao = $this->getServiceLocator()->get('user');
			$result = $userDao->updateUser($name, $aboutMe,$phone,$birthDay,$profession,$secPost,$renter,$gender,$this->getLoggedinUserId());
            if($result != null){
				$responseArray['result'] = result;
			} else {
				$this->updateIdentity();
			}
		}
		$responseArray['user'] =  $this->getUserFromSession();
		$layout = $this->layout();
		$layout->setTemplate('layout/loggedin')->setVariable('user', $this->getUserFromSession());
		$view = new ViewModel($responseArray);
		$view->setTemplate('/application/user/profile-change');
		return $view;

	}

	/**
	 * Profile image upload handling
	 */
	public function imageUploadAction()
	{
		$request = $this->getRequest();
		if ($request->isPost()) {
			// Make certain to merge the files info!
			$post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
			$fileName = $request->getFiles('profile-image');
				$fileName=$fileName['tmp_name'];
			// Form is valid, save the form!
			$imageService = new ImageService();
			$imageService->saveAllKindofImage($fileName, $this->getLoggedinUserId());
			$this->updateIdentity();
			// update the adaptor.

			$this->redirect()->toUrl('/');

		}
	}



    public function matchImageAction(){
        $request = $this->getRequest();
        if ($request->isPost()) {
            // Make certain to merge the files info!
            $post = array_merge_recursive($request->getPost()->toArray(), $request->getFiles()->toArray());
            $fileName = $request->getFiles('profile-image');
            $fileName=$fileName['tmp_name'];
            // Form is valid, save the form!
            $imageService = new ImageService();
           $face = $imageService->getFace($fileName);
            //$imageService->saveAllKindofImage($fileName, $this->getLoggedinUserId());
           // $this->updateIdentity();
            // update the adaptor.
            /*$response = $this->getResponse();
            $response->setContent($face);
            $response->getHeaders()
                ->addHeaderLine('Content-Transfer-Encoding', 'binary')
                ->addHeaderLine('Content-Type', 'image/png')
                ->addHeaderLine('Content-Transfer-Encoding', 'binary')
                ->addHeaderLine('Content-Length', mb_strlen($face));
            return $response; */
        } else {
            $layout = $this->layout()->setVariable('user', $this->getUserFromSession());
            $layout->setTemplate('layout/loggedin');
            //  var_dump($this->getUserFromSession());
            $view = new ViewModel(array('user' => $this->getUserFromSession()));
            $view->setTemplate('/application/user/face-image');
            return $view;
        }
    }


	/**
	 * Update handling,
	 *
	 * @return \Zend\View\Model\JsonModel
	 */
	public function updateAction()
	{
		$request = $this->getRequest();
		if ($request->isPost()) {
			$update = $request->getPost('update');

            /**
             * It will be either group or user.
             */
            $targetType = $request->getPost('targetType');

            /**
             *
             * target it will be id of the user or group. Here we might need to convert actual target id from name of
             * target id.
             *
             */
            $targetId = $request->getPost('target');


            $updateType = $request->getPost('updateType');

			$photoSet = $this->getUploadedFileXml('attached');

            $pollJson = null;
            if($request->getPost('pollJson') ){
                $pollJson = $request->getPost('pollJson');
            }

			$updateDao = $this->getServiceLocator()->get('update');
			$loginId = $this->getLoggedinUserId();
			$updateDao->saveUpdateData($update,$loginId,$photoSet,$request->getPost('title'),$updateType,$targetType,$pollJson,$targetId);
			$data = array(
				'result' => 'success'
			);
			return new JsonModel($data);
		}
	}


	/**
	 * Delete update
	 * @return \Zend\View\Model\JsonModel
	 */
	public function deleteUpdateAction()
	{
		$request = $this->getRequest();
		if ($request->isPost()) {
			$updateId = $request->getPost('updateId');
			$updateDao = $this->getServiceLocator()->get('update');
			$updateDao->deleteUpdate($updateId);
			return new JsonModel();
		}
	}

	/**
	 *
	 * @return \Zend\View\Model\JsonModel
	 */
	public function getUpdateAction()
	{
		$request = $this->getRequest();
		$lastSeenId = $request->getQuery('lastSeenId');
        $after = $request->getQuery('after') == 'false' ? '' : true;
        $limit = $request->getQuery('limit');
		$updateDao = $this->getServiceLocator()->get('update');

		$result = $updateDao->getUpdateData($lastSeenId, $this->getLoggedinUserId(),
            UpdateDao::$UPDATE_TYPE, $limit, $after);


		$updateService = new UpdateService();
		$finalResult = $updateService->processUpdate($result, $this->getLoggedinUserId());
		return new JsonModel($finalResult);
	}


    /**
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function getDiscussionAction()
    {
        $request = $this->getRequest();
        $lastSeenId = $request->getQuery('lastSeenId');
        $after = $request->getQuery('after') == 'false' ? '' : true;
        $limit = $request->getQuery('limit');
        $updateDao = $this->getServiceLocator()->get('update');

        $result = $updateDao->getUpdateData($lastSeenId, $this->getLoggedinUserId(),
            array_filter(UpdateDao::$UPDATE_TYPE, function ($key){
                return $key === 5;
            }) , $limit, $after);

        $updateService = new UpdateService();
        $finalResult = $updateService->processUpdate($result, $this->getLoggedinUserId());
        return new JsonModel($finalResult);
    }

    public function getDiscussionDetailAction(){
        $request = $this->getRequest();
        $discussionId = $request->getQuery('id');
        $updateDao = $this->getServiceLocator()->get('update');
        $updateService = new UpdateService();
        $finalResult = $updateService->processUpdate($updateDao->getUpdateDetail($discussionId), $this->getLoggedinUserId());
        return new JsonModel($finalResult);
    }

    /**
     *
     * @return \Zend\View\Model\JsonModel
     */
    public function getGroupAction()
    {
        $request = $this->getRequest();
        $userDao = $this->getServiceLocator()->get('user');
        $result = $userDao->getAllGroup($this->getLoggedinUserId());
        return new JsonModel($result);
    }


    public function responseAction(){
        $request = $this->getRequest();
        if ($request->isPost()) {
            $updateId = $request->getPost('updateId');
            $responseNo = $request->getPost('responseNo');
            $updateDao =  $this->getServiceLocator()->get('update');
            $responseID = $updateDao->savePollResponse($responseNo,$this->getLoggedinUserId(),null,$updateId);
             $data = array(
                'responseID' => $responseID
            );
            return new JsonModel($data);
        }
    }

    public function saveCommentAction(){
        $request = $this->getRequest();
        if ($request->isPost()) {
            $comment = $request->getPost('txt');
            $responseId = $request->getPost('responseID');
            $updateDao =  $this->getServiceLocator()->get('update');
            $responseID = $updateDao->savePollCommment($comment,$responseId);
            $data = array(
                'responseID' => $responseID
            );
            return new JsonModel($data);
        }
    }

    //

	/**
	 * @return JsonModel
	 * Get all discussion data.
	 */
	public function getDiscussion()
	{
		$request = $this->getRequest();
		$lastSeenId = $request . getQuery('lastSeenId');
		$updateService = new UpdateService();
		$updateDao = $this->getServiceLocator()->get('update');
		$result = $updateDao->getDiscussions($lastSeenId);
		return new JsonModel($result);
	}


	private function getUploadedFileXml($fieldName)
	{
		$request = $this->getRequest();
		$loginId = $this->getLoggedinUserId();
		$fileUploadArray = array();
		$fileUploadArray[XmlService::$NUM_FIELD_NAME] = 'file';
		if($request->getFiles($fieldName)) {
			foreach ($request->getFiles($fieldName) as $file) {
				$data = file_get_contents($file['tmp_name']);
				$extension = pathinfo($file['tmp_name'], PATHINFO_EXTENSION);
				$fileDao = $this->getServiceLocator()->get('file');
				$id = $fileDao->saveProfileImage($file['name'], $loginId, $data);
				$fi = new \finfo(FILEINFO_MIME);
				$mime_type = $fi->buffer(file_get_contents($file['tmp_name']));
				array_push($fileUploadArray, array(
					'id' => $id,
					'name' => $file['name'],
					'size' => $file['size'],
					'extension' => $extension,
					'type' =>$mime_type
				));
			}
		}
		if(count($fileUploadArray) == 1){
			return null;
		}
		$xmlw = new XmlService();
		return $xmlw->customXml($fileUploadArray, 'uploadedFiles');
	}

	/**
	 * @return JsonModel
	 * Get all discussion data.
	 */
	public function saveDiscussion()
	{
		$request = $this->getRequest();
		if ($request->isPost()) {
			$discussion = $request->getPost('dicussion');
			$title = $request->getPost('title');
			$targetType = $request->getPost('targetType');
			$targetId = $request->getPost('targetId');
			$photoSet = $this->getUploadedFileXml('attached');
			$loginId = $this->getLoggedinUserId();
			$updateDao =  $this->getServiceLocator()->get('update');
			$updateDao->saveUpdateData($discussion, $loginId, $photoSet, null, UpdateDao::$UPDATE_TYPE['DISCUSSION'], $targetType, $targetId);
			$data = array(
				'result' => 'success'
			);
			return new JsonModel($data);
		}
	}


    /**
     * @return JsonModel
     */
    public function saveUpdateAction()
    {
        $request = $this->getRequest();
        if ($request->isPost()) {
            $txt = $request->getPost('update');
            $id = $request->getPost('id');
            $updateDao =  $this->getServiceLocator()->get('update');
            $updateDao->saveUpdateTxt($txt, $id);
            $data = array(
                'update_txt' => $txt,
                'upid' => $id
            );
            return new JsonModel($data);
        }
    }

	/**
	 * @return ViewModel
	 */
	public function resetPasswordAction() {


		$req = $this->getRequest();

		if($req->isPost()){
			$password = $req->getPost ("password");
			$userDao = $this->getServiceLocator()->get("user");

            $ps = new PasswordService();
			$user = $userDao->resetPasswordById($this->getLoggedinUserId(), $ps->create_hash($password));

			$layout = $this->layout ();
			$layout->setTemplate ( 'layout/loggedin' )->setVariable('user', $this->getUserFromSession());;
			// Create and return a view model for the retrieved article
			$view = new ViewModel ();
			$view->setTemplate ( '/application/user/password-successful-change' );
			return $view;
		} else {
			$layout = $this->layout ();
			$layout->setTemplate ( 'layout/loggedin' )->setVariable('user', $this->getUserFromSession());;
			// Create and return a view model for the retrieved article
			$view = new ViewModel ();
			$view->setTemplate ( '/application/user/change-password-inside' );
			return $view;
		}

	}


    // poll responses
    function getPollResponsesAction(){
        $req = $this->getRequest();
        $updateId = $req->getQuery('updateId');
        $updateDao = $this->getServiceLocator()->get("update");
        return  new JsonModel($updateDao->getUpdateAgendaResponse($updateId));
    }

    function getVoteAction(){
        $request = $this->getRequest();
        $lastSeenId = $request->getQuery('lastSeenId');
        $after = $request->getQuery('after') == 'false' ? '' : true;
        $limit = $request->getQuery('limit');
        $updateDao = $this->getServiceLocator()->get('update');

        $result = $updateDao->getVoteUpdateData($lastSeenId, $this->getLoggedinUserId(),
            array_filter(UpdateDao::$UPDATE_TYPE, function ($key){
                return $key === 1;
            }) , $limit, $after);

        $updateService = new UpdateService();
        $finalResult = $updateService->processUpdate($result, $this->getLoggedinUserId());
        return new JsonModel($finalResult);
    }

}

?>
